package de.uni_saarland.coli.doclists.suffixtree;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import de.uni_saarland.coli.doclists.index.filesystem.DiscList;
import de.uni_saarland.coli.doclists.index.filesystem.FilesystemHelper;
import de.uni_saarland.coli.doclists.index.filesystem.IToBytes;

public class STreeNode implements IToBytes, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2485726806474048029L;
	private int nodeID;
	private int suffixNode;
	
	protected DiscList parentList;
	private Map<Integer, Set<Integer>> documentList;

	public STreeNode() {
		this.nodeID = 0;
		this.parentList = null;
		this.documentList = new HashMap<Integer, Set<Integer>>();
		this.suffixNode = -1;
	}

	public STreeNode(int id) {
		this.nodeID = id;
		this.parentList = null;
		this.documentList = new HashMap<Integer, Set<Integer>>();
		this.suffixNode = -1;
	}

	public STreeNode(byte[] bytes) {
		this.nodeID = FilesystemHelper.getIntFromByteArray(bytes, 0);
		this.documentList = new HashMap<Integer, Set<Integer>>();
		this.suffixNode = -1;
	}

	public int getNodeID() {
		return nodeID;
	}

	public void setNodeID(int nodeID) {
		this.nodeID = nodeID;
	}

	public int getSuffixNode() {
		return suffixNode;
	}

	public void setSuffixNode(int suffixNode) {
		this.suffixNode = suffixNode;
	}

	@Override
	public void setListIDX(int idx) {
		this.nodeID = idx;
	}

	@Override
	public int getListIDX() {
		return this.nodeID;
	}

	@Override
	public void setDistList(DiscList list) {
		this.parentList = list;
	}

	@Override
	public byte[] toBytes() {
		byte[] bytes = new byte[4];

		FilesystemHelper.addIntToByteArray(bytes, this.nodeID, 0);

		return bytes;
	}

	public void addDoc(Integer document, Integer start){
		if (!this.documentList.containsKey(document)) {
			this.documentList.put(document, new HashSet<Integer>());
		}
		Set<Integer> list = this.documentList.get(document);
		list.add(start);
	}
	
	public Set<Integer> getDocuments(){
		return this.documentList.keySet();
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Node ID: " + this.nodeID).append(" => ").append(this.suffixNode).append("\n");
		for (Entry<Integer, Set<Integer>> entry : this.documentList.entrySet()) {
			sb.append("\tDoc ").append(entry.getKey()).append(":");
			for (int pos : entry.getValue()) {
				sb.append(" ").append(pos);
			}
			sb.append("\n");
		}
		return sb.toString();
	}
}
